package outman.weibo.util;

import java.io.IOException;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.util.Log;
import android.widget.ImageView;

/**
 * 异步加载图像<br>
 * 图像保存规则：<br>
 * 保存头像：sdcard-pina-portrait 以用户id命名<br>
 * 保存微博图片：sdcard-pina-pre 以图片的url的最后一段命名
 * 
 * @author hy
 * 
 */
public class AsyncImageLoader {

    private static final String TAG = "AsyncImageLoader";
    // 将加载图片的线程锁定在5个
    private ExecutorService executorService = Executors.newFixedThreadPool(5);
    // 保留图片缓存
    private Map<Long, SoftReference<Drawable>> imageCache = new HashMap<Long, SoftReference<Drawable>>();

    private Handler handler = new Handler();
    private LocalMemory localMemory = new LocalMemory();

    private static AsyncImageLoader imageLoader;

    public static AsyncImageLoader getInstance() {
	if (null == imageLoader) {
	    imageLoader = new AsyncImageLoader();
	}
	return imageLoader;
    }

    /**
     * 加载头像
     * 
     * @param id
     *            用户id
     * @param url
     *            头像url
     * @param image
     *            头像ImageView
     */
    public void loadPortrait(final long id, final String url,
	    final ImageView imageView) {
	if (null == url || "".equals(url))
	    return;

	if (imageCache.containsKey(id)) {
	    SoftReference<Drawable> reference = imageCache.get(id);
	    if (null != reference) {
		if (null != reference.get()) {
		    Log.i(TAG, "load portrait not null");
		    imageView.setImageDrawable(reference.get());
		}
	    }
	}

	// 否则开新线程从本地或者网络地址加载图像
	executorService.submit(new Runnable() {

	    BitmapDrawable drawable = null;

	    @Override
	    public void run() {
		drawable = localMemory.getDrawable(String.valueOf(id),
			LocalMemory.PORTRAIT);
		if (null == drawable) {
		    // 若本地没有指定图片，则从网上下载
		    try {
			// 通过url获取图片
			drawable = new BitmapDrawable(new URL(url).openStream());
			// 加入软引用
			imageCache.put(id,
				new SoftReference<Drawable>(drawable));
			// 异步保存到本地
			AsyncImageSaver.getInstance().saveImage(drawable,
				String.valueOf(id), LocalMemory.PORTRAIT);

		    } catch (MalformedURLException e) {
			e.printStackTrace();
		    } catch (IOException e) {
			e.printStackTrace();
		    }
		}

		// handler在主线程加载图像
		handler.post(new Runnable() {

		    @Override
		    public void run() {

			imageView.setImageDrawable(drawable);
		    }
		});

	    }
	});

    }

    /**
     * 加载图片
     * 
     * @param id
     *            图片所在微博id
     * @param url
     *            图片url
     * @param imageView
     *            显示图片的ImageView
     */
    public void loadContentImage(final long id, final String url,
	    final ImageView imageView) {

    }
}
